import 'package:flutter/material.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/empty/empty_no_data.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_09_game/base/widget/base_get_builder.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/config/app_color.dart';

import 'web_logic.dart';

class WebPage extends StatelessWidget {
  WebPage({super.key});

  final WebLogic logic = Get.put(WebLogic());

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<WebLogic>(
      builder: (c) {
        return SafeArea(
            top: logic.isGame == false,
            bottom: logic.isGame == false,
            child: Stack(
              children: [
                Positioned.fill(child: _buildWebView(c)),
                Positioned(
                    top: 20.w + ScreenUtil().statusBarHeight,
                    left:  logic.isBet? null :20.w,
                    right:  logic.isBet? 20.w : null,
                    child: Visibility(
                        visible: logic.isGame,
                        child: GestureDetector(
                          onTap: () {
                            showDialogTips();
                          },
                          child: AutoImage(
                            Assets.commonGameHome,
                            width: 44.w,
                          ),
                        ))),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: _buildProgressBar(),
                ),
              ],
            ));
      },
    );
  }
  Widget _buildProgressBar() {
    return Obx(() {
      // 只在加载时显示进度条
      if (!logic.isWebLoading.value || logic.loadingProgress.value >= 1.0) {
        return const SizedBox.shrink();
      }

      return SizedBox(
        height: 4,
        child: LinearProgressIndicator(
          value: logic.loadingProgress.value,
          backgroundColor: AppColor.gameBorderColor,
          valueColor: const AlwaysStoppedAnimation<Color>(AppColor.primary),
        ),
      );
    });
  }

  /// 构建WebView
  Widget _buildWebView(WebLogic controller) {
    return Obx(() {
      if (controller.hasError.value) {
        return EmptyNoData.notYetView();
      }

      return InAppWebView(
        initialUrlRequest: URLRequest(url: WebUri(controller.url.value)),
        initialSettings: InAppWebViewSettings(
          userAgent: 'game_turntable_web',
          useShouldOverrideUrlLoading: true,
          mediaPlaybackRequiresUserGesture: false,
          allowsInlineMediaPlayback: true,
          javaScriptEnabled: true,
          domStorageEnabled: true,
          databaseEnabled: true,
          clearCache: false,
          cacheEnabled: true,
          supportZoom: true,
          builtInZoomControls: false,
          displayZoomControls: false,
          useHybridComposition: true,
        ),
        onWebViewCreated: (InAppWebViewController webViewController) {
          controller.webViewController = webViewController;
          // 注册JavaScript处理器
          controller.registerJavaScriptHandlers();
        },
        onConsoleMessage: (webViewController, ConsoleMessage message) {
          // message.message

          clog('onConsoleMessage   ${message.message}');
          // controller.consoleMessages.add(message.message);
        },
        onLoadStart: (InAppWebViewController webViewController, WebUri? url) {
          controller.onLoadStart(webViewController, url);
        },
        onLoadStop: (InAppWebViewController webViewController, WebUri? url) {
          controller.onLoadStop(webViewController, url);
        },
        onProgressChanged:
            (InAppWebViewController webViewController, int progress) {
          controller.onProgressChanged(webViewController, progress);
        },
        onLoadError: (InAppWebViewController webViewController, Uri? url,
            int code, String message) {
          controller.onLoadError(webViewController,
              url != null ? WebUri.uri(url) : null, code, message);
        },
        onLoadHttpError: (InAppWebViewController webViewController, Uri? url,
            int statusCode, String description) {
          controller.onLoadHttpError(webViewController,
              url != null ? WebUri.uri(url) : null, statusCode, description);
        },
        shouldOverrideUrlLoading: (controller, navigationAction) async {
          return NavigationActionPolicy.ALLOW;
        },
      );
    });
  }

  // showSheetTips() {
  //   CommonNormalSheet(
  //
  //       child: SingleChildScrollView(
  //         child: Column(
  //           children: logic.consoleMessages.map((str) {
  //             return Text(
  //               str,
  //               style: TextStyle(color: AppColor.textPrimary, fontSize: 14.sp),
  //             );
  //           }).toList(),
  //         ).marginOnly(bottom: 1000),
  //       )).show();
  // }

  showDialogTips() {
    Get.dialog(Center(
      child: Container(
        // width: 286.w,
        margin: EdgeInsets.symmetric(horizontal: 45.w),
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.w),
        decoration: BoxDecoration(
            color: AppColor.pageBgColor,
            borderRadius: BorderRadius.circular(16.w)),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              LocaleKeys.dialogTitleTip.tr,
              style: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.94),
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600),
            ),
            8.verticalSpaceFromWidth,
            Text(
              LocaleKeys.exitGameConfirm.tr,
              style: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.7),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400),
            ),
            20.verticalSpaceFromWidth,
            Row(
              children: [
                Expanded(
                    child: CommonButton(
                  height: 44.w,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  title: LocaleKeys.cancel.tr,
                  enable: false,
                  alwaysCanClick: true,
                  onClick: () {
                    Get.back();
                  },
                )),
                12.horizontalSpace,
                Expanded(
                    child: CommonButton(
                  height: 44.w,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  title: LocaleKeys.ok.tr,
                  onClick: () {
                    Get.back();
                    Get.back();
                  },
                )),
              ],
            )
          ],
        ),
      ),
    ));
  }
}
